<?php
namespace Plu\Library\Services\Redis\Props;

use Plu\Library\Services\ServiceBase;

class PropsRedis extends ServiceBase {

    static private $instance;

    // 使用ItemCostType 1龙币、2龙豆、3在线时长、4库存
    const ItemCostType = [
        'coin' => 1,
        'bean' => 2,
        'time' => 3,
        'inventory' => 4
    ];
    // 虚拟道具库存
    // u:item:{UserId}
    const KEY_OF_ITEM_INVENTORY = "u:item:%s";
    // 时长道具库存
    // item:inventory:{itemName}:{userId}
    const KEY_OF_TIME_INVENTORY = "item:inventory:%s:%s";
    // 道具类型 
    const CONFIG_KEY = "item:list";

    private $_configRedis;

    public function __construct(){
        $this->_configRedis = $this->getRedis('config');
    }

    // 获取道具信息
    public function getItemInfo($itemName) {
        $configKey = self::CONFIG_KEY;
        $item = $this->_configRedis->getFieldFromHashWithCache($configKey, $itemName);
        if ($item) {
            $itemInfo = json_decode($item, true);
            return $itemInfo;
        }
        return false;
    }

    // 获取道具库存数量
    public function getCount ($itemName, $userId) {
        return $this->incrby($itemName, $userId, 0);
    }

    // 消费道具库存
    public function consume ($itemName, $userId, $count) {
        return $this->incrby($itemName, $userId, - abs($count));
    }
    
    // 新增库存道具
    public function add ($itemName, $userId, $count) {
        return $this->incrby($itemName, $userId, abs($count));
    }

    private function incrby ($itemName, $userId, $count) {
        $costType = $this->getItemCostType($itemName);
        if ($costType === false) {
            return 0;
        }
        // 龙豆龙币走props 其他在pvuv
        if ($costType == self::ItemCostType['coin'] || $costType == self::ItemCostType['bean']) {
            $itemKey = sprintf(self::KEY_OF_ITEM_INVENTORY, $userId);
            $redis = $this->getRedis('props_cluster');
            return $redis->hIncrBy($itemKey, $itemName, $count);
        } 
        $itemKey = sprintf(self::KEY_OF_TIME_INVENTORY, $itemName, $userId);
        $redis = $this->getRedis('pvuv_cluster');
        return $redis->incrBy($itemKey, $count);
    }


    // 获取道具类型 
    private function getItemCostType($itemName) {
        $configKey = self::CONFIG_KEY;
        $itemInfo = $this->getItemInfo($itemName);
        if ($itemInfo) {
            $costType = $itemInfo['costType'];
            return $costType;
        }
        return false;
    }

    
}